<template>
    <div>
        <el-dialog
            :visible.sync="detailDialog"
            :modal="false"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            :fullscreen="true"
            :before-close="closeDialog"
            v-loading="loading"
        >
            <template slot="title">
                <div class="title-icon"></div>
                <span class="title-text">{{ info.title || '--' }}</span>
            </template>
            <div class="table-title">
                <span v-if="this.info.title == '监听表分布详情'"
                    >CDC监听表:<span style="color: #333333">{{ queryParams.sourceTable ? '【' + queryParams.sourceTable + '】' : '--' }}</span></span
                >

                <span v-else
                    >CDC监听表数:<span style="color: #333333">{{ tableTitleData.monitorTableNum }}张</span></span
                >

                <span
                    >CDC数据监听消息总数:<span style="color: #333333">{{ tableTitleData.monitorRecordNum }}条</span></span
                >
                <span
                    >监听成功消息数:<span style="color: #4b7902">{{ tableTitleData.successNum }}条</span></span
                >
                <span
                    >监听失败消息数:
                    <span style="color: #a30014">{{ tableTitleData.failedNum }}条</span>
                </span>
            </div>
            <div class="table-content" style="height: calc(100vh - 180px)">
                <vxe-table
                    border
                    :cell-style="getCellStyle"
                    :row-config="{ isHover: true }"
                    :sort-config="{
                        defaultSort: { field: sortProp, order: sortOrder, orders: ['desc', 'asc', null] },
                        remote: true,
                    }"
                    stripe
                    :filter-config="{ remote: true }"
                    @filter-change="handleFilter"
                    @sort-change="handleSort"
                    :data="tableData"
                    show-header-overflow
                    class="table"
                    header-align="center"
                    :key="columnsKey"
                    height="100%"
                    :tooltip-config="{ enterable: true }"
                >
                    <vxe-column
                        v-for="item in tableColumns"
                        :field="item.val"
                        :title="item.name"
                        :key="item.val"
                        :filters="item.filters"
                        :min-width="item.minWidth || '90px'"
                        show-overflow="tooltip"
                        sortable
                    >
                        <template #filter="{ $panel, column }" v-if="!checkFiltersParams.includes(item.val)">
                            <div>
                                <el-input
                                    ref="searchInput"
                                    class="my-input"
                                    type="type"
                                    v-for="(option, index) in column.filters"
                                    :key="index"
                                    v-model="option.data"
                                    @input="$panel.changeOption($event, !!option.data, option)"
                                />
                            </div>
                        </template>
                        <template slot-scope="scope">
                            <span v-if="item.type == 'func'" :style="getStyle(item.val, scope.row[item.val])">
                                {{ item.funcBody(scope.row[item.val], scope.row) || '--' }}
                            </span>
                            <!-- <span v-else-if="['kafkaValue', 'logInfo'].includes(item.val)">
                                    <el-tooltip placement="top" style="background: white">
                                        <div slot="content" style="padding: 0 10px 10px 0; width:200px">
                                            <div class="test" style="color: red">
                                                {{ scope.row[item.val] }}
                                            </div>
                                        </div>
                                        <span>{{ scope.row[item.val] || '--' }}</span>
                                    </el-tooltip>
                            </span> -->
                            <span v-else>
                                {{
                                    scope.row[item.val] === 0 || (scope.row[item.val] && (scope.row[item.val] + '').trim())
                                        ? scope.row[item.val]
                                        : '--'
                                }}
                            </span>
                        </template>
                    </vxe-column>
                </vxe-table>
            </div>
            <RiskPagination :paging="paging" @page-change="pageChange"></RiskPagination>
        </el-dialog>
    </div>
</template>

<script lang="ts">
import RiskPagination from '@/common/components/risk-pagination.vue';
import RiskTable from '@/common/components/risk-table.vue';
import { dateFormat, timeFormat } from '@/utils/tools';
import moment from 'moment';
import { Vue, Component, Prop, Watch } from 'vue-property-decorator';
import { getDetail, getMonitorCdcTrendDetail, getTableDistributeDetail } from '../api/cdc';

export interface pages {
    total?: number;
    pageSize?: number;
    currentPage?: number;
}

const dateChangeTypes = {
    I: '新增',
    U: '修改',
    D: '删除',
};

@Component({
    name: 'TableDetail',
    components: { RiskTable, RiskPagination },
})
export default class TableDetail extends Vue {
    @Prop() detailDialog: boolean;
    @Prop() info: any;
    @Prop() tableNames: any;
    // 类别
    @Prop() queryForm: any;

    dateFormat = dateFormat;
    timeFormat = timeFormat;
    columnsKey: number = 1;
    // 实际排序参数
    sortObj = {
        dataSource: 'C_DATA_SOURCE',
        tableName: 'C_TABLE_NAME',
        kafkaValue: 'LENGTH(C_KAFKA_VALUE)',
        monitorResultType: 'C_MONITOR_RESULT_TYPE',
        logInfo: 'LENGTH(C_LOG_INFO)',
        finishTimes: 'D_FINISH_TIMES',
        // receiveDate: '',
        dateChangeType: 'C_DATA_CHANGE_TYPE',
        primaryKeys: 'C_PRIMARY_KEYS',
    };
    resultPojo = { '0': '成功', '1': '失败', '2': '过滤' };
    // 条目状态
    tableColumns: any[] = [
        { name: '数据源', val: 'dataSource', sortable: true, search: true, filters: [{ data: '' }], align: 'center' },
        { name: '表名', val: 'tableName', sortable: true, search: true, filters: [{ data: '' }] },
        { name: '消息内容', val: 'kafkaValue', sortable: true },
        {
            name: '监听结果',
            val: 'monitorResultType',
            sortable: true,
            search: true,
            filters: [
                { label: '成功', value: '0' },
                { label: '失败', value: '1' },
                { label: '过滤', value: '2' },
            ],
            align: 'center',
            type: 'func',
            funcBody: value => this.resultPojo[value],
        },
        { name: '日志信息', val: 'logInfo', sortable: true, search: true, filters: [{ data: '' }] },
        { name: '监听耗时(ms)', val: 'finishTimes', sortable: true, align: 'right' },
        {
            name: '监听时间',
            val: 'receiveDate',
            sortable: true,
            align: 'center',
            type: 'func',
            funcBody: (value, row) => dateFormat(row['receiveDate']) + ' ' + timeFormat(row['receiveTime']) || '--',
        },
        {
            name: '消息变动类型',
            val: 'dateChangeType',
            sortable: true,
            search: true,
            filters: [
                { label: '新增', value: 'I' },
                { label: '修改', value: 'U' },
                { label: '删除', value: 'D' },
            ],
            align: 'center',
            type: 'func',
            funcBody: value => dateChangeTypes[value],
        },
        { name: '消息行主键', val: 'primaryKeys', sortable: true, search: true, filters: [{ data: '' }], align: 'center' },
    ];

    sortProp: string = 'modifyDateTime';
    sortOrder: string = 'desc'; // 排序方式
    columns: any[] = [];
    tableData: any[] = [];
    // 表格标题信息
    tableTitleData: any = {
        failedNum: null,
        successNum: null,
        monitorRecordNum: null,
        monitorTableNum: null,
        monitorTable: null,
    };
    loading: boolean = false;
    // queryParams: any = {};
    checkFiltersIndex: any[] = [2, 4]; // 复选框筛选
    checkFiltersParams = ['monitorResultType', 'dateChangeType']; // 注意添加
    paging: pages = {
        total: 0,
        pageSize: 25,
        currentPage: 1,
    };

    // 查询表单
    queryParams = {
        dataSource: '',
        logInfo: '',
        monitorResultType: [],
        sort: 'D_RECEIVE_DATE desc, D_RECEIVE_TIME desc',
        tableName: '',
        tableNames: [],
        endDate: moment().format('yyyyMMDD'),
        endTime: '',
        paging: {
            currentPage: 1,
            pageSize: 25,
        },
        sourceTable: '',
        startDate: moment().format('yyyyMMDD'),
        startTime: '',
        unit: 'hour',
        xdate: '',
        dateChangeType: [],
        primaryKeys: '',
    };
    iconDom = null;

    async mounted() {
        this.changeTable();
    }

    @Watch('info', { immediate: true, deep: true })
    onWatchInfo() {
        if (this.queryForm) {
            this.queryParams = JSON.parse(JSON.stringify(this.queryForm));
        }
        console.log(this.queryParams, 'kkkkk');

        this.queryParams.paging.pageSize = this.paging.pageSize;
        this.queryParams.paging.currentPage = this.paging.currentPage;
        this.queryParams.sort = '';
        this.getTableData();
    }

    // 改变筛选按钮
    changeTable() {
        this.$nextTick(() => {
            if (!this.iconDom) {
                let dom = document.querySelector('.table-content');
                this.iconDom = dom.querySelectorAll('.vxe-icon--funnel');
                for (let i = 0; i < this.iconDom.length; i++) {
                    if (!this.checkFiltersIndex.includes(i)) {
                        this.iconDom[i].className = 'vxe-filter--btn el-icon-search';
                    }
                }
            }
        });
    }

    // 获取监听消息走势详情数据
    queryCdcTrendDetail() {
        this.loading = true;
        getMonitorCdcTrendDetail(this.queryParams)
            .then((res: any) => {
                console.log(res, 'getMonitorCdcTrendDetail');
                if (res) {
                    for (const key in res) {
                        this.tableTitleData[key] = res[key];
                    }
                    this.tableData = res.pageResponse.list;
                    this.paging.total = res.pageResponse.total;
                }
                this.loading = false;
            })
            .catch(() => {
                this.tableData = [];
                this.tableTitleData = {
                    failedNum: null,
                    successNum: null,
                    monitorRecordNum: null,
                    monitorTableNum: null,
                    monitorTable: null,
                };
                this.loading = false;
            });
    }

    // 获取监听表分布详情
    queryTableDistributeDetail() {
        this.loading = true;
        getTableDistributeDetail(this.queryParams)
            .then((res: any) => {
                console.log(res, 'getTableDistributeDetail');
                if (res) {
                    for (const key in res) {
                        this.tableTitleData[key] = res[key];
                    }
                    this.tableData = res.pageResponse.list;
                    this.paging.total = res.pageResponse.total;
                }
                this.loading = false;
            })
            .catch(() => {
                this.tableData = [];
                this.tableTitleData = {
                    failedNum: null,
                    successNum: null,
                    monitorRecordNum: null,
                    monitorTableNum: null,
                };
                this.loading = false;
            });
    }

    // 获取监听数据详情
    queryDetail() {
        this.loading = true;
        getDetail(this.queryParams)
            .then((res: any) => {
                if (res) {
                    for (const key in res) {
                        this.tableTitleData[key] = res[key];
                    }
                    this.tableData = res.pageResponse.list;
                    this.paging.total = res.pageResponse.total;
                    // this.tableDetailMsg.returnData.total = res.total;
                }
                this.loading = false;
            })
            .catch(() => {
                this.tableData = [];
                this.tableTitleData = {
                    failedNum: null,
                    successNum: null,
                    monitorRecordNum: null,
                    monitorTableNum: null,
                };
                this.loading = false;
            });
    }

    resetFrom() {
        this.queryParams.tableName = '';
        this.queryParams.dataSource = '';
        this.queryParams.logInfo = '';
        this.queryParams.monitorResultType = [];
        this.queryParams.dateChangeType = [];
        this.queryParams.primaryKeys = '';
    }

    // 获取表格数据
    getTableData() {
        if (this.info.title == '监听消息走势详情') {
            this.queryParams.xdate = this.info.name;
            if (this.queryParams.unit == 'hour') {
                this.queryParams.xdate = this.queryParams.xdate.replace(/:/g, '');
            } else {
                this.queryParams.xdate = this.queryParams.xdate.substr(0, this.queryParams.xdate.length - 1);
            }

            this.queryParams.tableNames = [];
            this.queryCdcTrendDetail();
        } else if (this.info.title == '监听表分布详情') {
            this.queryParams.tableNames = [];
            this.queryParams.xdate = '';
            this.queryParams.unit = '';
            this.queryParams.sourceTable = this.info.name;
            this.queryTableDistributeDetail();
        } else if (this.info.title == '监听数据详情') {
            console.log(this.tableNames, 'jjj');
            this.queryParams.tableNames = this.tableNames;
            this.queryParams.xdate = '';
            this.queryDetail();
        }
    }

    /**
     * 表头筛选
     */
    handleFilter(obj) {
        this.paging.currentPage = 1;
        this.queryParams.paging.pageSize = this.paging.pageSize;
        this.queryParams.paging.currentPage = this.paging.currentPage;

        this.resetFrom();
        let filterList = obj.filterList;
        if (filterList.length) {
            filterList.forEach(ele => {
                let property = ele.property;
                if (this.checkFiltersParams.includes(property)) {
                    this.queryParams[ele.property] = ele.values;
                } else {
                    this.queryParams[ele.property] = ele?.datas[0] || '';
                }
            });
        }
        // else {
        //     this.resetFrom();
        // }
        // this.onWatchInfo();
        // this.queryDetail();
        this.getTableData();
    }

    /**
     * 表头排序
     */
    handleSort(column: any) {
        this.paging.currentPage = 1;
        this.queryParams.paging.currentPage = this.paging.currentPage;
        this.queryParams.paging.pageSize = this.paging.pageSize;
        this.sortProp = column.property;
        this.sortOrder = column.order;
        const sortType = column.order == 'asc' ? 'ASC' : column.order == 'desc' ? 'DESC' : '';
        let sort = '';
        if (sortType) {
            sort = this.handleSortField(column.property, sortType);
            console.log(sort, 'sort');
        }
        this.queryParams.sort = sort;
        // this.queryDetail();
        this.getTableData();
    }

    // 获取排序字段
    handleSortField(name: string, order: string): string {
        let value = '';
        let field = this.sortObj[name];
        value = field + ' ' + order;
        if (name == 'receiveDate') {
            value = 'D_RECEIVE_DATE ' + order + ', D_RECEIVE_TIME ' + order;
        }
        return value;
    }

    // 分页回调
    pageChange() {
        this.queryParams.paging.currentPage = this.paging.currentPage;
        this.queryParams.paging.pageSize = this.paging.pageSize;
        // this.onWatchInfo();
        this.getTableData();
    }

    // 关闭窗口
    closeDialog() {
        this.$emit('closeDialog');
    }

    // 对象转数组(仅用于过滤)
    changeObjToArr(obj) {
        let data = [];
        for (let key in obj) {
            data.push({ label: obj[key], value: key });
        }
        return data;
    }

    getStyle(val: string, value: string) {
        let color = '';
        if (val == 'monitorResultType') {
            color = value == '0' ? 'green' : value == '1' ? 'red' : '';
        }
        return { color: color };
    }

    getCellStyle({ column }) {
        let value = 'text-align:left';
        let obj = this.tableColumns.find(item => item.val == column.property);

        if (obj) {
            value = 'text-align: ' + (obj.align || 'left');
        }
        return value;
    }

    closeTooltip() {
        const dom = document.querySelector('.vxe-table--tooltip-wrapper');
        if (dom) {
            dom.remove();
        }
    }
}
</script>

<style lang="scss" scoped>
@import '@/pages/report/styles/common';
.my-input {
    margin: 10px;
    width: 150px;
}
.title-icon {
    width: 20px;
    height: 20px;
    display: inline-block;
    border: 4px solid #2288ff;
    border-radius: 50%;
    margin-right: 4px;
}
.title-text {
    display: inline-block;
    font-size: 16px;
    font-weight: 900;
}
.table-title {
    margin-bottom: 15px;
    > span {
        font-size: 16px;
        margin-right: 20px;
        > span {
            font-weight: 800;
            font-size: 16px;
        }
    }
    .table-title-content {
        color: #4b7902;
    }
}
// /deep/ .el-dialog.is-fullscreen {
//     margin-top: 6vh;
// }
/deep/ .el-dialog {
    .el-dialog__header {
        display: flex;
        align-items: center;
        background-color: #fff;
        border-bottom: 1px solid #ccc;

        .el-dialog__title {
            font-size: 16px;
            color: #333333;
        }
        .el-dialog__headerbtn .el-dialog__close {
            font-size: 24px;
            color: #515151;
        }
    }
    .el-dialog__body {
        max-height: 100%;
    }
}
/deep/ .el-dialog__wrapper {
    overflow: hidden;
}

.table /deep/ .vxe-cell .vxe-cell--title {
    font-size: 14px;
}
/deep/.c--tooltip {
    max-height: 50px !important;
    overflow: scroll;
}
// /deep/ .vxe-table--tooltip-wrapper .vxe-table--tooltip-content {
//     max-height: 200px;
//     overflow: auto;
// }
</style>
<style lang="scss">
// .vxe-table--tooltip-wrapper .vxe-table--tooltip-content {
//     max-height: 200px;
//     overflow: auto;
//     z-index: 2200;
// }
</style>
